import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:silver_flutter/event/user_events.dart';
import 'package:silver_flutter/event_bus.dart';
import 'package:silver_flutter/model/book.dart';
import 'package:silver_flutter/model/chapter.dart';
import 'package:silver_flutter/model/page.dart';
import 'package:silver_flutter/model/user.dart';
import 'package:silver_flutter/weixin_client.dart';

final kBaseUrl = 'http://dm.zuoent.com/api';
String _token;

Future<List<Book>> fetchBooks(String path) async {
  final headers = isLoggedIn()
      ? {
          HttpHeaders.AUTHORIZATION: _token,
        }
      : Map<String, String>();

  final resp = await http.get(
    '$kBaseUrl$path',
    headers: headers,
  );
  final List data = json.decode(resp.body);

  return data.map((e) => new Book.fromJson(e)).toList();
}

Future<List<Chapter>> fetchChapters(int bookId) async {
  final resp = await http.get('$kBaseUrl/books/$bookId/chapters');
  final List data = json.decode(resp.body);

  return data.map((e) => new Chapter.fromJson(e)).toList();
}

Future<List<Page>> fetchPages(int bookId, int chapterNumber) async {
  final headers = isLoggedIn()
      ? {
          HttpHeaders.AUTHORIZATION: _token,
        }
      : Map<String, String>();

  final resp = await http.get(
    '$kBaseUrl/books/$bookId/chapters/$chapterNumber/pages',
    headers: headers,
  );
  final List data = json.decode(resp.body);

  return data.map((e) => new Page.fromJson(e)).toList();
}

Future<Null> weixinLogin() async {
  String code = await new WeixinClient().login();
  final resp = await http.get('$kBaseUrl/login/weixin?code=$code');
  _token = resp.headers['authorization'];
  eventBus.fire(new UserLoggedInEvent());
}

Future<User> fetchUser() async {
  final resp = await http.get('$kBaseUrl/user', headers: {
    HttpHeaders.AUTHORIZATION: _token,
  });
  final data = json.decode(resp.body);

  return new User.fromJson(data);
}

Future<bool> fetchFavourite(int bookId) async {
  final resp = await http.get(
    '$kBaseUrl/user/favourites/$bookId',
    headers: {
      HttpHeaders.AUTHORIZATION: _token,
    },
  );

  return resp.statusCode == 200;
}

Future<Null> addToFavourites(int bookId) async {
  await http.post(
    '$kBaseUrl/user/favourites',
    headers: {
      HttpHeaders.AUTHORIZATION: _token,
      HttpHeaders.CONTENT_TYPE: ContentType.JSON.toString(),
    },
    body: bookId.toString(),
  );
}

Future<Null> removeFromFavourites(int bookId) async {
  await http.delete(
    '$kBaseUrl/user/favourites/$bookId',
    headers: {
      HttpHeaders.AUTHORIZATION: _token,
    },
  );
}

bool isLoggedIn() {
  return _token != null;
}

void logout() {
  _token = null;
  eventBus.fire(new UserLoggedOutEvent());
}
